package com.example.gifframecpp

import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.example.gifframecpp.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var mGifPath: String
    private lateinit var mGifHandler: GifHandler
    private var mBitmap: Bitmap? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        GifCopyManager(this).getGifFilePath {
            mGifPath = it!!
            binding.tvGifStatus.setText(it)
        }
    }

    override fun onResume() {
        super.onResume()

    }

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 0) {
                val delay: Int = mGifHandler.updateFrame(mBitmap!!)
                sendEmptyMessageDelayed(0, delay.toLong())
                binding.iv.setImageBitmap(mBitmap)
            }
        }
    }


    fun btn(view: View) {
        Thread {
            mGifHandler = GifHandler()
            mGifHandler.load(mGifPath)
            val height = mGifHandler.getHeight()
            val width = mGifHandler.getWidth()
            Log.i("GifHandler", "height: $height, width: $width")
            mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            val delay = mGifHandler.updateFrame(mBitmap!!)
            runOnUiThread {
                binding.iv.setImageBitmap(mBitmap)
                handler.sendEmptyMessageDelayed(0, delay.toLong());
            }
        }.start()
    }
}